package com.zrwl.poscloud.core.restapi.file.viewApi;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zrwl.poscloud.base.entity.FileInfo;
import com.zrwl.poscloud.commons.config.file.FileConfig;
import com.zrwl.poscloud.xo.service.FileInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RefreshScope
@RequestMapping("/pictureApi")
public class PictureApi {
    @Autowired
    FileInfoService fileInfoService;
    @Autowired
    FileConfig fileConfig;

    //uid查找完整路径

    //http://localhost:8061/pictureApi/IoReadImage
    @RequestMapping(value = "/IoReadImage", method = RequestMethod.GET)
    public String IoReadImage(HttpServletResponse response,String code) throws IOException {
        //
        QueryWrapper<FileInfo> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("code",code);
        FileInfo entity =fileInfoService.getOne(queryWrapper);
        String filePath=fileConfig.fullFilePath(entity.getOwnerCode(),entity.getFileType())+File.separator+entity.getFileName();//

        ServletOutputStream out = null;
        FileInputStream ips = null;
        try {
            //获取图片存放路径
            String imgPath = filePath;
            ips = new FileInputStream(new File(imgPath));
            response.setContentType("multipart/form-data");
            out = response.getOutputStream();
            //读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = ips.read(buffer)) != -1){
                out.write(buffer,0,len);
            }
            out.flush();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {
            out.close();
            ips.close();
        }
        return null;
    }




}
